from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import login, authenticate, logout as auth_logout, update_session_auth_hash
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.views.generic import ListView, CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.forms import PasswordChangeForm as AuthPasswordChangeForm

from .forms import LoginForm, CustomUserCreationForm, ProfileUpdateForm, AvatarUpdateForm, CustomPasswordChangeForm, \
    UserProfileForm
from .models import CustomUser
from main.models import TouristAttraction, SentimentComment, ScenicCategory, SentimentTag
from collect.models import Collect


# ==================== 认证相关视图 ====================


def reg(request):
    """用户注册"""
    if request.method == 'POST':
        form = CustomUserCreationForm(request.POST, request.FILES)
        if form.is_valid():
            user = form.save()
            login(request, user)
            messages.success(request, '注册成功！欢迎来到旅游舆情监测系统！')
            return redirect('users:log')  # 修正为 users:attractions_list
        else:
            messages.error(request, '注册失败，请检查表单信息！')
    else:
        form = CustomUserCreationForm()

    return render(request, 'main/reg.html', {'form': form})


def log(request):
    """用户登录"""
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            user = authenticate(username=username, password=password)

            if user is not None:
                login(request, user)
                messages.success(request, f'欢迎回来，{username}！')
                next_url = request.GET.get('next', 'main:attraction_list')  # 修正为 users:attractions_list
                return redirect(next_url)
            else:
                messages.error(request, '用户名或密码错误！')
    else:
        form = LoginForm()

    return render(request, 'main/log.html', {'form': form})


def logout(request):
    """用户退出"""
    auth_logout(request)
    messages.info(request, '您已成功退出登录。')
    return redirect('users:log')  # 修正为 users:attractions_list


@login_required
def cha(request):
    """修改密码"""
    if request.method == 'POST':
        form = AuthPasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            user = form.save()
            messages.success(request, '密码修改成功！')
            return redirect('users:center')
        else:
            messages.error(request, '密码修改失败，请检查表单！')
    else:
        form = AuthPasswordChangeForm(request.user)

    return render(request, 'main/cha.html', {'form': form})


@login_required
def center(request):
    """用户中心"""
    user = request.user

    # 用户统计信息
    user_stats = {
        'attractions_count': TouristAttraction.objects.filter(created_by=user).count(),
        'comments_count': SentimentComment.objects.filter(author=user, is_active=True).count(),
        'collections_count': Collect.objects.filter(user=user).count(),
    }

    # 最近创建的景点
    recent_attractions = TouristAttraction.objects.filter(
        created_by=user
    ).order_by('-created_at')[:5]

    # 最近评论
    recent_comments = SentimentComment.objects.filter(
        author=user,
        is_active=True
    ).select_related('attraction').order_by('-created_at')[:5]

    context = {
        'user_stats': user_stats,
        'recent_attractions': recent_attractions,
        'recent_comments': recent_comments,
    }

    return render(request, 'index/center.html', context)


@login_required
def profile_update(request):
    """更新个人资料"""
    if request.method == 'POST':
        form = UserProfileForm(request.POST, request.FILES, instance=request.user)
        if form.is_valid():
            form.save()
            messages.success(request, '个人资料更新成功！')
            return redirect('users:center')
        else:
            messages.error(request, '请检查表单中的错误')
    else:
        form = UserProfileForm(instance=request.user)

    return render(request, 'index/profile_update.html', {'form': form})


@login_required
def chahead(request):
    """修改头像"""
    if request.method == 'POST':
        form = AvatarUpdateForm(request.POST, request.FILES, instance=request.user)
        if form.is_valid():
            form.save()
            messages.success(request, '头像更新成功！')
            return redirect('users:center')
        else:
            messages.error(request, '头像更新失败，请重试')
    else:
        form = AvatarUpdateForm(instance=request.user)

    return render(request, 'index/chahead.html', {'form': form})


@login_required
def cha(request):
    """修改密码"""
    if request.method == 'POST':
        form = CustomPasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            user = form.save()
            update_session_auth_hash(request, user)  # 保持用户登录状态
            messages.success(request, '密码修改成功！')
            return redirect('users:center')
        else:
            messages.error(request, '请检查表单中的错误')
    else:
        form = CustomPasswordChangeForm(request.user)

    return render(request, 'main/cha.html', {'form': form})


# 您原有的登录、注册等视图函数
def user_login(request):
    """用户登录"""
    # 您原有的登录逻辑
    pass


def user_logout(request):
    """用户退出"""
    logout(request)
    messages.success(request, '您已成功退出登录')
    return redirect('main:attraction_list')


def register(request):
    """用户注册"""
    # 您原有的注册逻辑
    pass


@login_required
def chahead(request):
    """修改头像"""
    if request.method == 'POST':
        form = AvatarUpdateForm(request.POST, request.FILES, instance=request.user)
        if form.is_valid():
            form.save()
            messages.success(request, '头像修改成功！')
            return redirect('users:center')
        else:
            messages.error(request, '头像修改失败，请检查图片格式！')
    else:
        form = AvatarUpdateForm(instance=request.user)

    return render(request, 'index/chahead.html', {'form': form})


def active(request, encrypted_id):
    """用户激活（暂时保留）"""
    messages.info(request, '激活功能暂未开放')
    return redirect('users:log')


# ==================== 旅游景点管理类视图 ====================
class AttractionList(LoginRequiredMixin, ListView):
    """我创建的景点列表"""
    model = TouristAttraction
    template_name = 'main/attractions_list.html'
    context_object_name = 'attractions'
    paginate_by = 10

    def get_queryset(self):
        return TouristAttraction.objects.filter(
            created_by=self.request.user
        ).select_related('created_by').prefetch_related('categories', 'sentiment_tags').order_by('-created_at')

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['total_count'] = self.get_queryset().count()
        return context


class AttractionCreate(LoginRequiredMixin, CreateView):
    """创建景点"""
    model = TouristAttraction
    template_name = 'main/attraction_create.html'
    fields = [
        'name', 'description', 'location', 'city', 'province',
        'main_image', 'categories', 'sentiment_tags', 'status'
    ]

    def form_valid(self, form):
        form.instance.created_by = self.request.user
        messages.success(self.request, '景点创建成功！')
        return super().form_valid(form)

    def form_invalid(self, form):
        messages.error(self.request, '景点创建失败，请检查表单信息！')
        return super().form_invalid(form)

    def get_success_url(self):
        return reverse_lazy('users:attraction_list')  # 修正为 users:attractions_list

    def get_form(self, form_class=None):
        form = super().get_form(form_class)
        # 设置分类和标签的queryset
        form.fields['categories'].queryset = ScenicCategory.objects.all()
        form.fields['sentiment_tags'].queryset = SentimentTag.objects.all()
        return form

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['categories'] = ScenicCategory.objects.all()
        context['sentiment_tags'] = SentimentTag.objects.all()
        return context


class AttractionUpdate(LoginRequiredMixin, UpdateView):
    """更新景点"""
    model = TouristAttraction
    template_name = 'main/attraction_update.html'
    fields = [
        'name', 'description', 'location', 'city', 'province',
        'main_image', 'categories', 'sentiment_tags', 'status'
    ]

    def get_queryset(self):
        return TouristAttraction.objects.filter(created_by=self.request.user)

    def form_valid(self, form):
        messages.success(self.request, '景点更新成功！')
        return super().form_valid(form)

    def form_invalid(self, form):
        messages.error(self.request, '景点更新失败，请检查表单信息！')
        return super().form_invalid(form)

    def get_success_url(self):
        return reverse_lazy('users:attraction_list')  # 修正为 users:attractions_list

    def get_form(self, form_class=None):
        form = super().get_form(form_class)
        # 设置分类和标签的queryset
        form.fields['categories'].queryset = ScenicCategory.objects.all()
        form.fields['sentiment_tags'].queryset = SentimentTag.objects.all()
        return form

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['categories'] = ScenicCategory.objects.all()
        context['sentiment_tags'] = SentimentTag.objects.all()
        return context


class AttractionDelete(LoginRequiredMixin, DeleteView):
    """删除景点"""
    model = TouristAttraction
    template_name = 'main/attraction_delete.html'

    def get_queryset(self):
        return TouristAttraction.objects.filter(created_by=self.request.user)

    def delete(self, request, *args, **kwargs):
        messages.success(request, '景点删除成功！')
        return super().delete(request, *args, **kwargs)

    def get_success_url(self):
        return reverse_lazy('users:attraction_list')  # 修正为 users:attractions_list


